<?php

namespace App\Console\Commands\Common;

use AlibabaCloud\SDK\Dyvmsapi\V20170525\Models\ListHotlineTransferNumberResponseBody\data\values;
use App\Models\Article\ArticleModel;
use App\Models\Common\FileTranscodingJobModel;
use App\Service\Common\UploadTranscoding;
use Illuminate\Console\Command;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class UpdateFileTranscodingResult extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'common:update-file-transcoding-result';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新文件转码结果';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        FileTranscodingJobModel::query()
                               ->whereIn('status',
                                   [FileTranscodingJobModel::STATUS_WAIT, FileTranscodingJobModel::STATUS_FAIL])
                               ->get()
                               ->each(function (FileTranscodingJobModel $fileTranscodingJobModel) {
                                   $percent = UploadTranscoding::getWorkFile($fileTranscodingJobModel->jobId);
                                   if ($percent == 100) {
                                       //更新当前表的状态
                                       $fileTranscodingJobModel->status = FileTranscodingJobModel::STATUS_OK;
                                       $fileTranscodingJobModel->save();
                                       //更新转码后的字段
                                       $columns = Schema::getColumnListing((new $fileTranscodingJobModel->model)->getTable());
                                       $exist   = false;
                                       if (in_array('isDeleted', $columns)) {
                                           $exist        = true;
                                           $updateParams = [
                                               $fileTranscodingJobModel->updatedField => $fileTranscodingJobModel->filePathEncoded,
                                               'isDeleted'                            => 0,
                                           ];
                                       } else {
                                           $updateParams = [
                                               $fileTranscodingJobModel->updatedField => $fileTranscodingJobModel->filePathEncoded,
                                           ];
                                       }

                                       switch ($fileTranscodingJobModel->model) {
                                           case ArticleModel::class:
                                               self::articleTranscoding($fileTranscodingJobModel);
                                               break;
                                           default:
                                               $res = $fileTranscodingJobModel->model::query()
                                                                                     ->where('id',
                                                                                         $fileTranscodingJobModel->updatedModelId)
                                                                                     ->when($exist, function ($query) {
                                                                                         $query->withoutGlobalScope('isDel');
                                                                                     })
                                                                                     ->update($updateParams);
                                               dump($res);
                                               break;
                                       }
                                   }
                               });
    }

    /**
     * 文章视频转码
     *
     * @param FileTranscodingJobModel $fileTranscodingJobModel
     */
    public static function articleTranscoding(FileTranscodingJobModel $fileTranscodingJobModel)
    {
        try {
            DB::beginTransaction();
            $articleModel = ArticleModel::query()->withoutGlobalScope('isDel')
                                        ->where('id', $fileTranscodingJobModel->updatedModelId)
                                        ->lockForUpdate()
                                        ->first();

            if (!empty($articleModel->transcodingVideoDetail)) {
                $transcodingVideoDetail = collect(
                    json_decode($articleModel->transcodingVideoDetail, true)
                );
                $transcodingVideoDetail = $transcodingVideoDetail
                    ->map(function ($row) use ($fileTranscodingJobModel) {
                        if (str_contains($row["original"],
                            $fileTranscodingJobModel->filePath)) {
                            $row["transcodingVideoDetail"] = collect($row["transcodingVideoDetail"])
                                ->map(function ($detail) use (
                                    $fileTranscodingJobModel,
                                    $row
                                ) {
                                    if ($detail["jobId"] == $fileTranscodingJobModel->jobId) {
                                        $detail["url"] = str_replace(
                                            $fileTranscodingJobModel->filePath,
                                            $fileTranscodingJobModel->filePathEncoded,
                                            $row["original"]
                                        );
                                    }
                                    return $detail;
                                })->values()->toArray();
                        }
                        return $row;
                    })->values()->toJson(JSON_UNESCAPED_UNICODE);
            }
            $articleModel->transcodingVideoDetail = $transcodingVideoDetail;
            $articleModel->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            logException(
                "文章转码脚本执行失败",
                $exception,
                $fileTranscodingJobModel->toArray(),
                true,
                true
            );
        }
    }
}
